package com.jy.modules.cims.common.open.api.crypt;

import java.nio.charset.Charset;
import java.security.MessageDigest;

import com.jy.modules.cims.common.open.api.exception.JieYueApiException;

public class MD5Crypt {
	private Charset charset = Charset.forName("UTF-8");

	public MD5Crypt() {
	}

	public MD5Crypt(Charset charset) {
		this.charset = charset;
	}

	public MD5Crypt(String charset) {
		this(Charset.forName(charset));
	}

	public String md5(String inputText) {
		return md5Encrypt(inputText, "md5");
	}

	private String md5Encrypt(String inputText, String algorithmName) {
		if ((inputText == null) || ("".equals(inputText.trim()))) {
			throw new IllegalArgumentException("请输入要加密的内容");
		}
		if ((algorithmName == null) || ("".equals(algorithmName.trim()))) {
			algorithmName = "md5";
		}
		try {
			MessageDigest m = MessageDigest.getInstance(algorithmName);
			m.update(inputText.getBytes(this.charset));
			byte[] s = m.digest();
			return hex(s);
		} catch (Exception e) {
			throw new JieYueApiException(inputText + "的md5加密失败", e);
		}
	}

	private String hex(byte[] arr) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < arr.length; i++) {
			sb.append(Integer.toHexString(arr[i] & 0xFF | 0x100).substring(1, 3));
		}
		return sb.toString();
	}
}
